package com.taoyige.ui;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.taoyige.AppContext;
import com.taoyige.AppException;
import com.taoyige.R;
import com.taoyige.adapter.ListOrdersAdapter;
import com.taoyige.bean.Notice;
import com.taoyige.bean.Order;
import com.taoyige.bean.OrderList;
import com.taoyige.common.StringUtils;
import com.taoyige.common.UIHelper;
import com.taoyige.widget.LoadingDialog;
import com.taoyige.widget.NewDataToast;
import com.taoyige.widget.PullToRefreshListView;

/**
 * 已付款待收货订单
 * @author zhuxun
 * @version 1.0
 * @date 2014-11-25 上午9:56:40
 */
public class NotReceiptOrdersActivity extends BaseActivity {
	
	private AppContext appContext;
	private Handler lvOrderHandler;
	private LoadingDialog loading;
	
	private ImageButton returnBack;
	private ImageButton homePage;
	private TextView userHeadText;
	private LinearLayout linearlayout;
	private LinearLayout orderNull;
	private Button nowTaoyige;
	private LinearLayout order;
	private Button lookorder;
	private Button okorder;
	
	private ImageButton orderDetail1;
	private ImageButton orderDetail2;
	private Button orderDetail3;
	
	private PullToRefreshListView lvOrder;
	private List<Order> lvOrderData = new ArrayList<Order>();
	private int lvOrderSumData;
	private ListOrdersAdapter lvOrdersAdapter;
	
	private View lvOrder_footer;
	private TextView lvOrder_foot_more;
	private ProgressBar lvOrder_foot_progress;
	
	private Button trackOrder;
	private String curOrderCatalog = "0";
	private LinearLayout unpaid_body;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_order_main);
		
		this.initView();
		appContext=(AppContext) this.getApplication();
		if (!appContext.isNetworkConnected()){
			unpaid_body.setVisibility(View.INVISIBLE);
			returnBack.setOnClickListener(homeListener);
			homePage.setOnClickListener(homeListener);
			return;
		}
		 curOrderCatalog=appContext.getLoginUid();
		 //for test
		  if(curOrderCatalog.isEmpty()){
			  curOrderCatalog = "1-2088002318420134";
		  }
		this.initOrderListView();
		this.initData();
	}
	
	private void initData(){
		lvOrderHandler = this.getLvHandler(lvOrder, lvOrdersAdapter,lvOrder_foot_more,lvOrder_foot_progress, AppContext.PAGE_SIZE);
		// 加载资讯数据
		if (lvOrderData.isEmpty()) {
			loadLvOrderData(curOrderCatalog, 0, lvOrderHandler,UIHelper.LISTVIEW_ACTION_INIT);
		}
	}
	private void initView(){
		returnBack=(ImageButton)findViewById(R.id.user_hear_return_back);
		homePage=(ImageButton)findViewById(R.id.user_hear_homePage);
		userHeadText=(TextView)findViewById(R.id.user_hear_text);
		userHeadText.setText("待收货订单");
		
		returnBack.setOnClickListener(returnListener);
		homePage.setOnClickListener(homeListener);
		unpaid_body=(LinearLayout)findViewById(R.id.unpaid_body);
	}

	private void showTaoyige(){
		linearlayout=(LinearLayout)findViewById(R.id.pay_main_order);
		
		LayoutInflater inflater=getLayoutInflater();
		View view = inflater.inflate(R.layout.order_null, null);
		nowTaoyige=(Button)view.findViewById(R.id.order_null_id_null);
		linearlayout.addView(view);
		nowTaoyige.setOnClickListener(homeListener);
	}
	
	/**
	 * 初始化订单列表
	 */
	private void initOrderListView() {
		
		//trackOrder=(Button) findViewById(R.id.nopay_order_orderstatus);
		//trackOrder.setText("跟踪订单");
		
		lvOrdersAdapter = new ListOrdersAdapter(this, lvOrderData,R.layout.order_list_common);
		
		lvOrder_footer = getLayoutInflater().inflate(R.layout.listview_footer,null);
		lvOrder_foot_more = (TextView) lvOrder_footer.findViewById(R.id.listview_foot_more);
		lvOrder_foot_progress = (ProgressBar) lvOrder_footer.findViewById(R.id.listview_foot_progress);
		
		lvOrder = (PullToRefreshListView) findViewById(R.id.frame_listview_order);
		
		lvOrder.addFooterView(lvOrder_footer);
		lvOrder.setAdapter(lvOrdersAdapter);

		lvOrder.setOnScrollListener(new AbsListView.OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				lvOrder.onScrollStateChanged(view, scrollState);

				// 数据为空--不用继续下面代码了
				if (lvOrderData.isEmpty())
					return;

				// 判断是否滚动到底部
				boolean scrollEnd = false;
				try {
					if (view.getPositionForView(lvOrder_footer) == view.getLastVisiblePosition())
						scrollEnd = true;
				} catch (Exception e) {
					scrollEnd = false;
				}

				int lvDataState = StringUtils.toInt(lvOrder.getTag());
				if (scrollEnd && lvDataState == UIHelper.LISTVIEW_DATA_MORE) {
					lvOrder.setTag(UIHelper.LISTVIEW_DATA_LOADING);
					lvOrder_foot_more.setText(R.string.load_ing);
					lvOrder_foot_progress.setVisibility(View.VISIBLE);
					// 当前pageIndex
					int pageIndex =lvOrderSumData / AppContext.PAGE_SIZE;
					loadLvOrderData(curOrderCatalog+"", pageIndex, lvOrderHandler,UIHelper.LISTVIEW_ACTION_SCROLL);
				}
			}

			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				lvOrder.onScroll(view, firstVisibleItem, visibleItemCount,
						totalItemCount);
			}
		});
		
		lvOrder.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {
			public void onRefresh() {
				loadLvOrderData(curOrderCatalog+"", 0, lvOrderHandler,
						UIHelper.LISTVIEW_ACTION_REFRESH);
			}
		});
	}
	
	/**
	 * 获取listview的初始化Handler
	 * 
	 * @param lv
	 * @param adapter
	 * @return
	 */
	private Handler getLvHandler(final PullToRefreshListView lv,
			final BaseAdapter adapter, final TextView more,
			final ProgressBar progress, final int pageSize) {
		return new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what >=1) {
					// listview数据处理
					Notice notice = handleLvData(msg.what, msg.obj, msg.arg2,
							msg.arg1);

					if (msg.what < pageSize) {
						lv.setTag(UIHelper.LISTVIEW_DATA_FULL);
						adapter.notifyDataSetChanged();
						//more.setText(R.string.load_full);
						more.setVisibility(TextView.INVISIBLE);
					} else if (msg.what == pageSize) {
						lv.setTag(UIHelper.LISTVIEW_DATA_MORE);
						adapter.notifyDataSetChanged();
						more.setText(R.string.load_more);

					}
					// 发送通知广播
					/*
					if (notice != null) {
						UIHelper.sendBroadCast(lv.getContext(), notice);
					}
					if (isClearNotice) {
						ClearNotice(curClearNoticeType);
						isClearNotice = false;
						curClearNoticeType = 0;
					}*/
				} else if (msg.what == -1) {
					// 有异常--显示加载出错 & 弹出错误消息
					lv.setTag(UIHelper.LISTVIEW_DATA_MORE);
					more.setText(R.string.load_error);
					((AppException) msg.obj).makeToast(NotReceiptOrdersActivity.this);
				}
				if (adapter.getCount() == 0) {
					lv.setTag(UIHelper.LISTVIEW_DATA_EMPTY);
					more.setVisibility(View.GONE);
					showTaoyige();
				}
				progress.setVisibility(ProgressBar.GONE);
				if (msg.arg1 == UIHelper.LISTVIEW_ACTION_REFRESH) {
					lv.onRefreshComplete(getString(R.string.pull_to_refresh_update)
							+ new Date().toLocaleString());
					lv.setSelection(0);
				} else if (msg.arg1 == UIHelper.LISTVIEW_ACTION_INIT) {
					lv.onRefreshComplete();
					lv.setSelection(0);
				}
			}
		};
	}
	

	/**
	 * listview数据处理
	 * 
	 * @param what
	 *            数量
	 * @param obj
	 *            数据
	 * @param objtype
	 *            数据类型
	 * @param actiontype
	 *            操作类型
	 * @return notice 通知信息
	 */
	private Notice handleLvData(int what, Object obj, int objtype,
			int actiontype) {
		Notice notice = null;
		switch (actiontype) {
		case UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG:
		case UIHelper.LISTVIEW_ACTION_REFRESH:
		case UIHelper.LISTVIEW_ACTION_INIT:
			int newdata = 0;// 新加载数据-只有刷新动作才会使用到
			if(objtype==UIHelper.LISTVIEW_DATATYPE_ORDER){
				OrderList tlist = (OrderList) obj;
				notice = tlist.getNotice();
				lvOrderSumData = what;
				if (actiontype == UIHelper.LISTVIEW_ACTION_REFRESH) {
					if (lvOrderData.size() > 0) {
						for (Order order1 : tlist.getList()) {
							boolean b = false;
							for (Order order2 : lvOrderData) {
								if (order1.getId().equals( order2.getId())) {
									b = true;
									break;
								}
							}
							if (!b)
								newdata++;
						}
					} else {
						newdata = what;
					}
				}
				lvOrderData.clear();// 先清除原有数据
				lvOrderData.addAll(tlist.getList());
			}
			
			if (actiontype == UIHelper.LISTVIEW_ACTION_REFRESH) {
				// 提示新加载数据
				if (newdata > 0) {
					NewDataToast
							.makeText(
									this,
									getString(R.string.new_data_toast_message,
											newdata), appContext.isAppSound())
							.show();
				} else {
					NewDataToast.makeText(this,
							getString(R.string.new_data_toast_none), false)
							.show();
				}
			}
			
			break;
			
		case UIHelper.LISTVIEW_ACTION_SCROLL:
			switch (objtype) {
			case UIHelper.LISTVIEW_DATATYPE_ORDER:
				OrderList tlist = (OrderList) obj;
				notice = tlist.getNotice();
				
				lvOrderSumData += what;
				if (lvOrderData.size() > 0) {
					for (Order order1 : tlist.getList()) {
						boolean b = false;
						for (Order order2 : lvOrderData) {
							if (order1.getId() == order2.getId()) {
								b = true;
								break;
							}
						}
						if (!b)
							lvOrderData.add(order1);
					}
				} else {
					lvOrderData.addAll(tlist.getList());
				}
				break;
			}
			
			break;
		}
		return notice;
	}
	
	
	
	
	/**
	 * 线程加载订单数据
	 * 
	 * @param uid
	 * @param pageIndex
	 *            当前页数
	 * @param handler
	 *            处理器
	 * @param action
	 *            动作标识
	 */
	private void loadLvOrderData(final String uid, final int pageIndex,final Handler handler, final int action) {
		
		new Thread() {
			public void run() {
				Message msg = new Message();
				boolean isRefresh = false;
				if (action == UIHelper.LISTVIEW_ACTION_REFRESH|| action == UIHelper.LISTVIEW_ACTION_SCROLL)
					isRefresh = true;
				try {
					OrderList list = appContext.getPaidOrderList(uid,pageIndex, isRefresh);
					if(list!=null&&list.getResult().getErrorCode()==200){
						msg.what =list.getList().size();
						msg.obj = list;
					}else{
						msg.what =0;
						msg.obj = list;
					}
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				msg.arg1 = action;
				msg.arg2 = UIHelper.LISTVIEW_DATATYPE_ORDER;
				if (curOrderCatalog.equals(uid))
					handler.sendMessage(msg);
			}
		}.start();
	}
	
	private View.OnClickListener homeListener = new View.OnClickListener(){
		@Override
		public void onClick(View v){
			UIHelper.showHomePage(v.getContext());
			finish();
		}
	};
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean flag = true;
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			UIHelper.showUser(NotReceiptOrdersActivity.this);
			finish();
		} 
		return flag;
	}
	
	private View.OnClickListener returnListener = new View.OnClickListener(){
		@Override
		public void onClick(View v){
			UIHelper.showUser(v.getContext());
			finish();
		}
	};
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
